package cinema.Dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@SuppressWarnings("serial")
public class AbstractDAO<E> implements Serializable{
	
	@PersistenceContext(unitName = "cinemaConnection")
    EntityManager em;
	
	private Class<E> entityClass;
	
	public AbstractDAO(Class<E> entityClass) {
        super();
        this.entityClass = entityClass;
    }

    public AbstractDAO() {
    }

    public List<E> findAll(){
		return em.createQuery("select e from " + entityClass.getSimpleName() + " e" , entityClass).getResultList();
	}
	
	public E findById(int id){
		return em.find(entityClass, id);
	}
	
	public void save( E entity ){
      em.persist( entity );
   }
 
   public void update( E entity ){
	   em.merge( entity );
   }
 
   public void delete( E entity ){
	   E toBeRemoved = em.merge(entity);
	   em.remove(toBeRemoved);
   }
   
   public void deleteById( int entityId ){
      E entity = findById( entityId );
      delete( entity );
   }
}